import javax.swing.tree.TreeNode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

//二叉树的锯齿形层序遍历
//测试链接 https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/
public class ZigzagLevelOrder {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList();

        if(root == null) return ret;
        queue.add(root);

        boolean flg = false; //true正序，false逆序
        while(!queue.isEmpty()) {
            int n = queue.size();
            List<Integer> temp = new ArrayList<>();

            for(int i = 0; i < n; i++) {
                TreeNode node =  queue.poll();
                if(!flg) {
                    temp.add(node.val);
                }
                else{
                    temp.add(0,node.val);
                }

                if(node.left != null) {
                    queue.add(node.left);
                }
                if(node.right != null) {
                    queue.add(node.right);
                }

            }
            flg = !flg;
            ret.add(temp);
        }
        return ret;
    }
}
